package cn.tworice.system.service.user;

import cn.hutool.core.util.DesensitizedUtil;
import cn.tworice.mybatis.query.LambdaQueryWrapperX;
import cn.tworice.mybatis.query.MPJLambdaWrapperX;
import cn.tworice.mybatis.vo.PageParam;
import cn.tworice.system.dao.user.UserDao;
import cn.tworice.system.dao.user.po.UserDO;
import cn.tworice.system.dao.user.po.UserInfoDTO;
import cn.tworice.system.dao.user.po.SystemUserInfoDO;
import cn.tworice.common.util.excel.InductsListenerService;
import cn.tworice.system.dao.user.SystemUserInfoDao;
import cn.tworice.system.service.role.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class SystemUserInfoService extends ServiceImpl<SystemUserInfoDao, SystemUserInfoDO> implements InductsListenerService<SystemUserInfoDO> {

    @Resource
    private SystemUserInfoDao dao;

    @Resource
    private UserDao userDao;

    @Resource
    private RoleService roleService;

    public Map<String,Object> getPage(PageParam pageParam, SystemUserInfoDO entity) {
        return dao.selectPage(pageParam, new LambdaQueryWrapperX<SystemUserInfoDO>()
                .eqIfPresent(SystemUserInfoDO::getId, entity.getId())
                .eqIfPresent(SystemUserInfoDO::getUserId, entity.getUserId())
        );
    }
    
    @Override
    public boolean saveBatch(List<SystemUserInfoDO> list) {
        list.forEach(item -> item.setCreateTime(System.currentTimeMillis()));
        return dao.insertBatch(list,list.size());
    }

    public UserInfoDTO info(String userId) {
        UserInfoDTO userInfoDTO = userDao.selectJoinOne(UserInfoDTO.class, new MPJLambdaWrapperX<UserDO>()
                .select(UserDO::getNickName, UserDO::getLoginName, UserDO::getPhone, UserDO::getEmail)
                .selectAll(SystemUserInfoDO.class)
                .leftJoin(SystemUserInfoDO.class, SystemUserInfoDO::getUserId,UserDO::getId)
                .eq(UserDO::getId, userId));
        // 初始化角色信息
        userInfoDTO.setRoles(roleService.getRoleListByUid(userId));
        return userInfoDTO;
    }

    /**
     * 获取脱敏用户信息
     * @param userId 用户标识
     * @return 用户脱敏信息
     */
    public SystemUserInfoDO blurInfo(String userId) {
        UserInfoDTO info = this.info(userId);
        info.setAdminPhone(DesensitizedUtil.mobilePhone(info.getAdminPhone()));
        info.setAdminEmail(DesensitizedUtil.email(info.getAdminEmail()));
        return info;
    }

    /**
     * 根据用户ID删除用户信息
     * @param ids 用户ID
     */
    public void removeByAdminId(String[] ids) {
        dao.delete(new LambdaQueryWrapperX<SystemUserInfoDO>()
                .in(SystemUserInfoDO::getUserId, Arrays.asList(ids))
        );
    }
}